// @flow
import React, { Component } from 'react'
import styles from './RegionSetting.css'
import { Button } from 'antd'
import RegionSettingGrid from './RegionSettingGrid'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

type Props = {
  history: Object
}
type States = {
  users: Array<Object>,
  total: number,
  current: number,
  pageSize: number
}
class RegionSetting extends Component {
  props: Props
  state: States
  getRegionSetting: Function
  addRegionSetting: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      users: [],
      total: 0,
      current: 1,
      pageSize: 20
    }
    this.getRegionSetting = this.getRegionSetting.bind(this)
    this.addRegionSetting = this.addRegionSetting.bind(this)
  }

  componentDidMount () {
    this.getRegionSetting(this.state.current, this.state.pageSize)
  }

  getRegionSetting (page: number, pageSize: number) {
    universalFetch(`${__SERVICE_API__}sys/regions?pageNum=${page}&pageSize=${pageSize}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          current: page,
          total: json.pageInfo ? json.pageInfo.total : 1,
          users: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  addRegionSetting () {
    this.props.history.push('/business/customer-add')
  }
  render () {
    const { users, current, pageSize, total } = this.state
    return (
      <div className={styles['main']}>
        <div className={styles['action']}>
          <Button onClick={this.addRegionSetting}>添加区域</Button>
        </div>
        <RegionSettingGrid {...{
          current,
          pageSize,
          total,
          refreshRegionSettings: this.getRegionSetting,
          rowData: users
        }} />
      </div>
    )
  }
}

export default RegionSetting
